<script setup lang="ts">
  import { PropType, ref, watch } from 'vue'
  import HDrawer from '@/components/common/drawer/HDrawer.vue'
  // import {
  //   useUpdateOrderInfo,
  //   useGetOrderInfoBeforeEdit,
  // } from '@/services/pages/order/useOrderDetail'

  // const { form, loading: updateInfoLoading, save, resetForm } = useUpdateOrderInfo()
  import * as _ from 'lodash'
  import { empPageSelecct } from '@/api/organize'
  import useFactorySelectPageService from '@/views/order/new/services/factorySelectPage'
  import { workModuleTypePageSelect, workModuleWayPageSelect, orderUpdateInfo } from '@/api/order'
  import { orderAnnexUpload } from '@/api/upload'
  import { ElMessage, UploadFile } from 'element-plus'
  import { OrderDetail } from '@/viwes/order/list/odetail/types'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  const visible = defineModel<boolean>('modelValue', { default: false })

  const CascaderProps = ref({
    value: 'id',
    label: 'name',
    children: 'selectVos',
    disabled: 'select',
    checkStrictly: true,
  })

  const basicData = ref<OrderDetail | null>(null)

  const fileList = ref([])

  const updateInfoLoading = ref(false)

  const sources = ref([
    { title: '平台系统报单', value: 1 },
    { title: '扫码报单', value: 2 },
    { title: '小程序报单', value: 3 },
    { title: 'APP报单', value: 4 },
    { title: '平台代商家报单', value: 7 },
    { title: '乐开伙伴云', value: 9 },
  ])

  // 规则
  const rules = ref({})

  // 获取图片
  let pass = ref(true)
  const handleChange: UploadProps['onChange'] = (uploadFile: UploadFile) => {
    if (fileList.value.length >= 10) {
      if (pass.value) {
        ElMessage({
          showClose: true,
          message: `数量不能超过10!`,
          type: 'error',
          duration: 3000,
        })
        pass.value = false
      }

      return
    }
    pass.value = true
    let { uid, name } = uploadFile.raw
    let tmp = {
      uid,
      name,
      img: window.URL.createObjectURL(uploadFile.raw),
      file: uploadFile.raw,
      upDatatime: new Date(Date.now()).toISOString().split('T')[0],
    }
    fileList.value.push(tmp)
  }
  // 删除图片
  const deleteItem = (index) => {
    fileList.value = fileList.value.filter((o, i) => i != index)
  }

  const dialogContract = ref(false) //文件查看弹窗
  const file = ref() //文件
  // 查看图片
  const lookFile = (val) => {
    file.value = val
    dialogContract.value = true
  }

  //监听弹窗关闭时销毁 iframe内存
  watch(dialogContract, (n) => {
    if (!n) {
      file.value = 'about:blank'
    }
  })

  /**
   * 工单客服组下拉列表查询
   */
  const loading = ref(false)
  const customers = ref([])
  const getworkTeamPageSelect = _.throttle((val: string) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    loading.value = true
    empPageSelecct(data).then((res) => {
      if (res.data.success) {
        customers.value = res.data.data.rows
      }
      loading.value = false
    })
  }, 500)

  const valueSele = ref('')
  const changeValue = () => {
    getFactorySelectPageFn({ limit: 0, name: valueSele.value, page: 0 })
  }

  // 使用品牌商家下拉数据服务
  const { factoryOptional, getFactorySelectPageLoading, getFactorySelectPageFn } =
    useFactorySelectPageService

  //工单分类下拉远程搜索
  const inputChangeType = async (val) => {
    if (basicData.value.moduleId) {
      await getworkModuleTypePageSelect(val, basicData.value.moduleId)
    }
  }

  // 处理方式下拉远程搜索
  const inputChangeMethod = async (val) => {
    if (val && basicData.value.moduleId) {
      await getworkModuleWayPageSelect(val, basicData.value.moduleId)
    }
  }

  const methodss = ref([])
  //  通过模块id 获取处理方式
  const getworkModuleWayPageSelect = async (val, id) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    const res = await workModuleWayPageSelect(data, id)
    methodss.value = res.data.data.rows
  }
  // 工单分类下拉框出现/隐藏时触发
  const showType = ref(false)
  const changeType = async () => {
    showType.value = !showType.value
    if (!showType.value) {
      if (!(basicData.value.type instanceof Array)) {
        await getworkModuleTypePageSelect('', basicData.value.moduleId)
      }
    }
  }
  // 处里方式下拉框出现/隐藏时触发
  const changeMmethod = async () => {
    showType.value = !showType.value
    if (!showType.value) {
      if (!(basicData.value.method instanceof Array)) {
        await getworkModuleWayPageSelect('', basicData.value.moduleId)
      }
    }
  }

  const types = ref([])
  //工单分类下拉数据
  const getworkModuleTypePageSelect = async (val, id) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    const res = await workModuleTypePageSelect(data, id)
    types.value = res.data.data.rows
  }

  const open = (params) => {
    visible.value = true
    basicData.value = { ...params }
    fileList.value = params.orderImages.map((item) => ({
      name: '',
      img: item,
    }))

    // getworkTeamPageSelect(basicData.value.emp)
    // getFactorySelectPageFn({ limit: 0, name: basicData.value.factory, page: 0 })
    // // getworkModuleWayPageSelect()
    // changeType()
    // changeMmethod()

    // getworkModuleTypePageSelect()
  }
  const emits = defineEmits(['update'])
  // 保存
  const onSaveClick = async () => {
    const data = { ...basicData.value }
    const type = data.type
    const method = data.method
    // 工单模块分类
    if (type?.length > 0) {
      type.map((o, i) => {
        if (i == 0) {
          data.oneTypeId = o
        }
        if (i == 1) {
          data.twoWayId = o
        }
        if (i == 2) {
          data.threeTypeId = o
        }
      })
    }
    // 工单模块方式
    if (method?.length > 0) {
      method.map((o, i) => {
        if (i == 0) {
          data.oneWayId = o
        }
        if (i == 1) {
          data.twoWayId = o
        }
        if (i == 2) {
          data.threeWayId = o
        }
      })
    }
    // 判断是否有图片
    if (fileList.value?.length > 0) {
      let imageList = fileList.value.map((o) => {
        return o.file
      })
      // 上传图片
      data.imageVos = []
      const orderAnnexUploadRes = await orderAnnexUpload(imageList)
      if (orderAnnexUploadRes.data.success) {
        for (let i = 0; i < orderAnnexUploadRes.data.data.rows.length; i++) {
          data.imageVos.push({ id: null, image: orderAnnexUploadRes.data.data.rows[i] })
        }
      } else {
        ElMessage({
          message: orderAnnexUploadRes.data.message,
          type: 'error',
        })
      }
    }

    try {
      updateInfoLoading.value = true
      const res = await orderUpdateInfo(data)
      updateInfoLoading.value = false
      if (res.data.success) {
        visible.value = false
        emits('update')
        HMessage.success('操作成功')
      } else {
        HMessageBox.error(res.data.message)
      }
    } catch (error) {
      updateInfoLoading.value = false
    }
  }

  const closeModal = () => {
    visible.value = false
  }

  watch(visible, (value) => {
    if (value) {
      basicData.value = { ...props.orderDetail }
    }
  })

  defineExpose({
    open,
  })
</script>

<template>
  <h-drawer
    v-model="visible"
    title="修改工单信息"
    :loading="updateInfoLoading"
    :width="800"
    unit="px"
    @close="closeModal"
  >
    <el-form
      ref="formInstance"
      class="modal_form_content"
      label-position="top"
      :model="basicData"
      :rules="rules"
      inline-message
      scroll-to-error
    >
      <!-- 工单来源 -->
      <!-- <el-form-item label="工单来源"
                    prop="source">
        <el-select v-model="basicData.source"
                   @change="changeSou"
                   class="w200"
                   placeholder="请选择">
          <el-option v-for="(item, index) in sources"
                     :key="index"
                     :label="item.title"
                     :value="item.value" />
        </el-select>
      </el-form-item> -->

      <!-- 描述 -->
      <el-form-item label="描述" prop="content">
        <el-input
          v-model="basicData.content"
          :rows="2"
          class="form-control"
          maxlength="500"
          placeholder="请输入描述"
          show-word-limit
          type="textarea"
        />
      </el-form-item>

      <!-- 上传附件 -->
      <!-- <el-form-item label="工单图片上传附件">
                <div class="upload_file">
                  <el-upload
                    v-model="fileList"
                    :auto-upload="false"
                    :on-change="handleChange"
                    :show-file-list="false"
                    accept="image/*,.pdf"
                    action="#"
                    drag
                    multiple
                  >
                    <el-icon class="up_icon">
                      <UploadFilled />
                    </el-icon>
                    <div>点击上传图片或者文件(最多10个附件)</div>
                  </el-upload>
                  <ul class="ul_list">
                    <li v-for="(item, index) in fileList" :key="index" class="li_item">
                      <div class="li_item_left">
                        <img
                          v-if="item.name.replace(/.+\./, '') == 'pdf'"
                          :src="pdf"
                          alt=""
                          style="width: 30px; height: 30px"
                          @click.stop="lookFile(item.img)"
                        />
                        <el-image
                          v-else
                          :preview-src-list="[item.img]"
                          :src="item.img"
                          fit="contain"
                          style="width: 30px; height: 30px"
                        />
                        <span class="pic_name">{{ item.name }}</span>
                      </div>
                      <el-icon size="16" style="cursor: pointer" @click.stop="deleteItem(index)">
                        <Delete />
                      </el-icon>
                    </li>
                  </ul>
                </div>
              </el-form-item> -->

      <!-- 受理客服 -->
      <!-- <el-form-item label="受理客服">
        <el-select v-model="basicData.empId"
                   :loading="loading"
                   :filter-method="getworkTeamPageSelect"
                   class="w200"
                   clearable
                   filterable
                   placeholder="请选择"
                   remote-show-suffix>
          <el-option :value="0"
                     label="按规则分配">
            <div style="display: flex; justify-content: space-between; align-items: center">
              <span>按规则分配</span> <span style="color: #fb9337">系统</span>
            </div>
          </el-option>
          <el-option v-for="item in customers"
                     :key="item.name"
                     :label="item.name"
                     :value="item.id" />
        </el-select>
      </el-form-item> -->

      <!-- 关联商家 -->
      <!-- <el-form-item v-if="basicData.source === 7"
                    label="关联商家"
                    prop="factoryId">
        <el-select class="w200"
                   @change="; (valueSele = ''), changeValue"
                   @clear="changeValue"
                   v-model="basicData.factoryId"
                   clearable
                   placeholder="请选择"
                   :loading="getFactorySelectPageLoading">
          <template #header>
            <div style="display: flex; gap: 5px">
              <el-input v-model="valueSele"
                        @keyup.enter="changeValue" />
              <h-plain-button @click="changeValue">搜索</h-plain-button>
            </div>
          </template>
          <el-option v-for="item in factoryOptional"
                     :key="item.name"
                     :label="item.name"
                     :value="item.id" />
        </el-select>
      </el-form-item> -->

      <!-- 工单分类 -->
      <!-- <el-form-item label="工单分类">
        <el-cascader v-model="basicData.type"
                     :before-filter="inputChangeType"
                     :options="types"
                     :props="CascaderProps"
                     class="w200"
                     clearable
                     filterable
                     placeholder="请选择"
                     @visible-change="changeType" />
      </el-form-item> -->

      <!-- 处理方式 -->
      <!-- <el-form-item label="处理方式">
        <el-cascader v-model="basicData.method"
                     :before-filter="inputChangeMethod"
                     :options="methodss"
                     :props="CascaderProps"
                     class="w200"
                     clearable
                     filterable
                     placeholder="请选择"
                     @visible-change="changeMmethod" />
      </el-form-item> -->
    </el-form>

    <template #footer>
      <HButton is-modal type="primary" @click="onSaveClick">保存</HButton>
      <HButton is-modal @click="closeModal">关闭</HButton>
    </template>

    <!-- 文件查看 -->
    <el-dialog
      v-model="dialogContract"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :draggable="true"
      title="查看附件"
    >
      <iframe
        :src="`${file}`"
        frameborder="0"
        height="100%"
        style="height: 700px"
        width="100%"
      ></iframe>
    </el-dialog>
  </h-drawer>
</template>

<style scoped lang="scss">
  .upload_file {
    width: 100%;

    :deep(.el-upload-dragger) {
      padding: 0;
      font-size: 12px;
      height: 40px;
      line-height: 10px !important;
      color: #999;
    }

    .up_icon {
      color: #ccc;
      font-size: 24px;
    }

    .ul_list {
      display: flex;
      max-height: 230px;
      overflow-y: auto;
      justify-content: space-between;
      flex-wrap: wrap;
      margin-top: 10px;
      padding: 0 6px;

      .li_item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border: 1px solid #e4e7ed;
        padding: 4px 10px;
        width: calc(50% - 40px);
        color: #999;
        font-size: 12px;
        margin-top: 10px;
        padding-right: 10px;
        border-radius: 2px;

        .li_item_left {
          display: flex;
          align-items: center;
          width: calc(100% - 15px);

          .pic_name {
            padding-left: 10px;
            color: #000;
            margin-right: 5px;
            text-overflow: ellipsis;
            white-space: nowrap;
            width: 70%;
            overflow: hidden;
          }
        }
      }
    }
  }
</style>
